package com.sc.site.consultComment;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.sc.dal.common.pagination.PaginationBean;
import com.sc.dal.mapper.consultComment.ConsultCommentMapper;
import com.sc.dal.model.consultComment.ConsultComment;
import com.sc.dal.model.member.Member;
import com.sc.service.consultComment.ConsultCommentService;
import com.sc.service.order.OrderService;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Common;
import com.sc.util.data.DataUtil;
import com.sc.util.data.FileUtil;
import com.sc.util.data.SessionContainer;
import com.sc.util.exception.ExceptionEnum;
import com.sc.util.exception.ScBizException;
/**
 * 咨询、评论、浏览管理
 * @author xiongyong
 * @2017.4.15 9:20:34 AM
 * 
 */
@Controller
@RequestMapping(value="/consultComment")
public class ConsultCommentController {
	private final Logger logger = LoggerFactory.getLogger(ConsultCommentController.class); 
	
	@Autowired
	private ConsultCommentService consultCommentService;
	
	@Autowired
	private OrderService orderService;
	
	/**
	 * 根据条件查询咨询、评价、浏览内容数据
	 * type : 1、咨询内容 2、评价晒单 3、我的足迹',
	 * @param request
	 * @return
	 */
	@RequestMapping(value="queryConsult")
	@ResponseBody
	public Object queryConsult(HttpServletRequest request,Integer currPage, Integer pageSize){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		int totalRecords = 0;	//总记录数
		int totalPage = 0;		//总页数
		List<Map<String, Object>> resultList = null;
		String type = request.getParameter("type");
		String accountName = request.getParameter("accountName"); //获取用户名
		if(type==null || "".equals(type)){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
			logger.warn("type查询参数为空！");
		}else{
			try {
				Map<String,Object> paramMap = new HashMap<String,Object>();
				paramMap.put("type", type);
				String goodsId = request.getParameter("goodsId");
				if(goodsId!=null && !"".equals(goodsId)){
					paramMap.put("goodsId", goodsId);
				}
				if(accountName!=null && !"".equals(accountName)){
					paramMap.put("accountName", accountName);
				}
				//我的足迹不等3，如其下判断
				if(!"3".equals(type)){
					String status = request.getParameter("status");
					//status【咨询状态：0：全部数据 1：已回复  2：未回复  】【评价状态：0：全部 1：差评  2：中评  3：好评  4：有图评价】 
					if(status!=null && !"".equals(status)){
						paramMap.put("status", status);
					//status =4  根据条件查询有图片的数据
					/*}else if(status!=null && !"".equals(status) && "4".equals(status)){
						paramMap.put("filePicture", "");
					//status =0  根据条件查询所有的数据
					}*/
					}else{
						paramMap.put("status", null);
					}
				}else{
					paramMap.put("status", "status");
				}
				PaginationBean<Map<String,Object>> pagination = this.consultCommentService.getPagingDatas(paramMap, currPage, pageSize, "count","select",ConsultCommentMapper.class);
				resultList = pagination.getPageList();//返回数据
				/**组合追加的评论数据***/
				for (int i = 0; i < resultList.size(); i++) {
					ConsultComment comment = (ConsultComment) resultList.get(i);
					Map<String, Object> map = new HashMap<String, Object>();
					Integer id = comment.getId();
					map.put("id", id);
					if(goodsId!=null && !"".equals(goodsId)){
						map.put("goodsId", goodsId);
					}
					List<ConsultComment> idList = consultCommentService.selectParentList(map);
					comment.setChildrenList(idList);
				}
				totalRecords = pagination.getTotalRecords();//返回行数
				totalPage = pagination.getTotalPage();
				int currentPage = pagination.getCurrentPage();//获取当前页数
				resultMap.put("totalPage",totalPage);
				resultMap.put("totalRecords",totalRecords);
				resultMap.put("resultList", resultList);
				resultMap.put("currentPage", currentPage);
			} catch (Exception e) {
				logger.error("查询咨询、评价信息数据异常"+e);
				throw new ScBizException("查询咨询、评价信息数据异常！", e);
			}
		}
		return resultMap;
	}
	/**
	 * @Title: deleteCommentsByIds
	 * @Description 删除用户离开提交的图片评论信息
	 * @date 2017年5月24日上午08:55
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="/deleteCommentsByIds")
	@ResponseBody
	@Transactional
	public Map<String,Object> deleteCommentsByIds(String ids){

		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		try{
			if(Common.isEmpty(ids)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			String[] idsArr = ids.split(",");
			for(String id: idsArr){
			    int j = consultCommentService.deleteConsult(Integer.valueOf(id));
				if (j > 0) {
					DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_SUCCESS);
				} else {
					DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_INSERT);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultMap;
	}
	/**
	 * @Title: deleteConsultCommentPic
	 * @Description 删除商品评论的图片
	 * @date 2017年5月24日上午08:55
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="/deleteConsultCommentPic")
	@ResponseBody
	public Map<String ,Object> deleteConsultCommentPic(HttpServletRequest request,Integer commentId,String filePicture){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		try{
			if(commentId == null || Common.isEmpty(filePicture)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
		    ConsultComment comment = new ConsultComment();
		    comment.setId(commentId);
		    
		    if(filePicture.equals("filePicture")){
		        comment.setFilePicture(filePicture);
		    }else if(filePicture.equals("filePicture2")){
		        comment.setFilePicture2(filePicture);		    	
		    }else if(filePicture.equals("filePicture3")){
		        comment.setFilePicture3(filePicture);		    	
		    }
		    int j = consultCommentService.updateByPrimaryKeySelective(comment);
			if (j > 0) {
				DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_SUCCESS);
			} else {
				DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_INSERT);
				return resultMap;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultMap;
	}
	/**
	 * @Title: addConsultCommentPic
	 * @Description 异步上传订单商品评价图片
	 * @date 2017年5月12日上午12:38
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="/addConsultCommentPic")
	@ResponseBody
	public Map<String,Object> addConsultCommentPic(MultipartHttpServletRequest requests,HttpServletRequest request,Integer goodsId,String orderId){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		String commentPath = "imgUrl"; //图片存储相对路径
		List<String> imgUrls=new ArrayList<String>(); //图片相对路径集合
		try{
			Member member = SessionContainer.getSessionMember(request);
			if(requests.getFiles("files")  == null || goodsId == null || Common.isEmpty(orderId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			 //取出一个list的multipartfile 
	        List<MultipartFile> files = requests.getFiles("files");  
	        for (int i = 0;i< files.size() ; i++) {  
	        	MultipartFile multipartFile = files.get(i);
	            String imgUrl  =  FileUtil.upload(multipartFile, "filePicture"+i, commentPath, ConfigBeanAdapter.fileSaveAddress);
	            imgUrls.add(imgUrl);
	        } 
	        ConsultComment record = new ConsultComment();
	        Date date = new Date();
	        record.setType("2");
	        record.setOrderId(orderId);
	        record.setGoodsId(goodsId);
	        record.setCreater(member.getmId());
	        record.setCreaterName(member.getmName());
	        record.setCreateTime(date);
	        record.setModifier(member.getmId());
	        record.setModifyTime(date);
	        if(imgUrls.size()>0)
	           record.setFilePicture(imgUrls.get(0));
	        if(imgUrls.size()>1)
		       record.setFilePicture2(imgUrls.get(1));
	        if(imgUrls.size() >2)
		       record.setFilePicture3(imgUrls.get(2));
	        int j = 0;
			ConsultComment parentRecord = consultCommentService.selectParentConsultComment(record);	//第一次评论	
			if(parentRecord != null){
				if(Common.isEmpty(parentRecord.getConsultContent())){ //第一次评论图片上传
					if(imgUrls.size() == 1){
						if(Common.isEmpty(parentRecord.getFilePicture())){
							parentRecord.setFilePicture(imgUrls.get(0));
						}
						if(Common.isEmpty(parentRecord.getFilePicture2())){
							parentRecord.setFilePicture2(imgUrls.get(0));
						}
						if(Common.isNotEmpty(parentRecord.getFilePicture())&&Common.isNotEmpty(parentRecord.getFilePicture2()) &&Common.isEmpty(parentRecord.getFilePicture3())){
							record.setFilePicture3(imgUrls.get(0));
						}
					}else if(imgUrls.size() == 2){
						if(Common.isEmpty(parentRecord.getFilePicture()) && Common.isEmpty(parentRecord.getFilePicture2()) && Common.isEmpty(parentRecord.getFilePicture3()) ){
							record.setFilePicture(imgUrls.get(0));
							record.setFilePicture2(imgUrls.get(1));
						}else if(Common.isNotEmpty(parentRecord.getFilePicture()) &&  Common.isEmpty(parentRecord.getFilePicture2()) && Common.isEmpty(parentRecord.getFilePicture3())){
							record.setFilePicture2(imgUrls.get(0));
							record.setFilePicture3(imgUrls.get(1));
						}else if(Common.isNotEmpty(parentRecord.getFilePicture()) &&  Common.isNotEmpty(parentRecord.getFilePicture2()) && Common.isEmpty(parentRecord.getFilePicture3())){
							record.setFilePicture3(imgUrls.get(0));
						}
					}else if(imgUrls.size() == 3){
						if(Common.isEmpty(parentRecord.getFilePicture()) && Common.isEmpty(parentRecord.getFilePicture2()) && Common.isEmpty(parentRecord.getFilePicture3()) ){
							parentRecord.setFilePicture(imgUrls.get(0));
							parentRecord.setFilePicture2(imgUrls.get(1));
							parentRecord.setFilePicture3(imgUrls.get(2));
						}else if(Common.isNotEmpty(parentRecord.getFilePicture()) && Common.isEmpty(parentRecord.getFilePicture2()) && Common.isEmpty(parentRecord.getFilePicture3())){
							parentRecord.setFilePicture2(imgUrls.get(0));
							parentRecord.setFilePicture3(imgUrls.get(1));
						}else if( Common.isNotEmpty(parentRecord.getFilePicture()) && Common.isNotEmpty(parentRecord.getFilePicture2()) && Common.isEmpty(parentRecord.getFilePicture3())){
							parentRecord.setFilePicture3(imgUrls.get(0));
						}
					}
					j = consultCommentService.updateByPrimaryKeySelective(parentRecord);
				}else{ //追评的图片上传
					record.setParentId(parentRecord.getId());
					List<ConsultComment> list = consultCommentService.selectCommentByParam(record);
					ConsultComment newRecord = null;
					if(list != null && list.size() >0){
						newRecord =  consultCommentService.selectCommentByParam(record).get(0);
					}
					if(newRecord == null){ //追评第一次图片上传
						j = consultCommentService.insertByConsultComment(record);
					}else{

						if(imgUrls.size() == 1){
							if(Common.isEmpty(newRecord.getFilePicture())){
								newRecord.setFilePicture(imgUrls.get(0));
							}
							if(Common.isEmpty(newRecord.getFilePicture2())){
								newRecord.setFilePicture2(imgUrls.get(0));
							}
							if(Common.isNotEmpty(newRecord.getFilePicture())&&Common.isNotEmpty(newRecord.getFilePicture2()) &&Common.isEmpty(newRecord.getFilePicture3())){
								newRecord.setFilePicture3(imgUrls.get(0));
							}
						}else if(imgUrls.size() == 2){
							if(Common.isEmpty(newRecord.getFilePicture()) && Common.isEmpty(newRecord.getFilePicture2()) && Common.isEmpty(newRecord.getFilePicture3()) ){
								newRecord.setFilePicture(imgUrls.get(0));
								newRecord.setFilePicture2(imgUrls.get(1));
							}else if(Common.isNotEmpty(newRecord.getFilePicture()) &&  Common.isEmpty(newRecord.getFilePicture2()) && Common.isEmpty(newRecord.getFilePicture3())){
								newRecord.setFilePicture2(imgUrls.get(0));
								newRecord.setFilePicture3(imgUrls.get(1));
							}else if(Common.isNotEmpty(newRecord.getFilePicture()) &&  Common.isNotEmpty(newRecord.getFilePicture2()) && Common.isEmpty(newRecord.getFilePicture3())){
								newRecord.setFilePicture3(imgUrls.get(0));
							}
						}else if(imgUrls.size() == 3){
							if(Common.isEmpty(newRecord.getFilePicture()) && Common.isEmpty(newRecord.getFilePicture2()) && Common.isEmpty(newRecord.getFilePicture3()) ){
								newRecord.setFilePicture(imgUrls.get(0));
								newRecord.setFilePicture2(imgUrls.get(1));
								newRecord.setFilePicture3(imgUrls.get(2));
							}else if(Common.isNotEmpty(newRecord.getFilePicture()) && Common.isEmpty(newRecord.getFilePicture2()) && Common.isEmpty(newRecord.getFilePicture3())){
								newRecord.setFilePicture2(imgUrls.get(0));
								newRecord.setFilePicture3(imgUrls.get(1));
							}else if( Common.isNotEmpty(newRecord.getFilePicture()) && Common.isNotEmpty(newRecord.getFilePicture2()) && Common.isEmpty(newRecord.getFilePicture3())){
								newRecord.setFilePicture3(imgUrls.get(0));
							}
						}
						newRecord.setParentId(parentRecord.getId());
						j = consultCommentService.updateByPrimaryKeySelective(newRecord);
					}
				}
				
			}else{
				j = consultCommentService.insertByConsultComment(record);
			}
			if(j>0){
				/*//修改订单评论状态
				Order order =new Order();
				order.setOrderId(orderId);
				order.setIsComment(Constants.OrderDetail.OrderStatus.IS_COMMENTB);
				order.setIsDelete(Constants.IS_DELETEA);
				orderService.updateOrder(order);*/
				ConsultComment newRecord = consultCommentService.selectCommentByParam(record).get(0);
				if(record != null){
					resultMap.put("orderId", orderId);
					resultMap.put("goodsId", goodsId);
					resultMap.put("commentId", newRecord.getId());
				}
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
			}
		
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);			
		} catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
		}
		return resultMap;
	}
	/**
	 * @title updateConsultComments
	 * @deprecated 订单评价、追加评价图片上传
	 * type : 1、咨询内容 2、评价晒单 3、我的足迹',
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/updateConsultComments")
	@ResponseBody
	public Map<String, Object>  updateConsultComments(HttpServletRequest request,String param) throws UnsupportedEncodingException{
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();

		try {
			param = URLDecoder.decode(param, "UTF-8");
			Member member = SessionContainer.getSessionMember(request);
			if (param == null) {
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				logger.warn("json的param参数传递出错！");
				return resultMap;
			} else {
				List<ConsultComment> list = JSON.parseArray(param,
						ConsultComment.class);
				String orderId = "";
				if (list != null && list.size() > 0) {
					for (ConsultComment model : list) {
						String type = model.getType();
						if (model == null|| type == null|| "".equals(type) || ("2".equals(type)&& Common.isEmpty(model.getOrderId())) ) {
							DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_PARAM);
							return resultMap;
						}
						orderId = model.getOrderId();
						ConsultComment record = this.getByConsultComment(model,member.getmId());
						if(model.getId() == null){//无图提交
							int j =0;
							ConsultComment parentComment = consultCommentService.selectParentConsultComment(record);
							if(parentComment != null){
								record.setParentId(parentComment.getId());
							}
							j = consultCommentService.insertByConsultComment(record);
							if (j > 0) {
								// 修改订单评论状态
								orderService.updateOrderAndOrderDetailCommentStatus(orderId,record.getGoodsId());
								DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_SUCCESS);
							} else {
								DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_INSERT);
								return resultMap;
							}
						}else{//图片已提交
							int j = consultCommentService.updateByPrimaryKeySelective(record);
							if (j > 0) {
								// 修改订单评论状态
								orderService.updateOrderAndOrderDetailCommentStatus(orderId,record.getGoodsId());
								DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_SUCCESS);
							} else {
								DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_INSERT);
								return resultMap;
							}
						}
					}
				}
				
			}
		} catch (Exception e) {
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
		}
		return resultMap;
	}
	//封装评论信息
	public ConsultComment getByConsultComment(ConsultComment model,String memberId){
		ConsultComment record = new ConsultComment();
		if(model.getId() != null)
		   record.setId(model.getId());
		//评价内容
		record.setGoodsId(model.getGoodsId()); //商品ID
		record.setOrderId(model.getOrderId());
		record.setSpecInfo(model.getSpecInfo()); //商品规格信息
		//全部   1：差评  2：中评  3：好评
		record.setStatus(model.getStatus());			
		record.setGoodsSatisfaction(model.getGoodsSatisfaction()); //商品评分
		record.setConsultContent(model.getConsultContent()); //评价内容
		record.setLogisticsScore(model.getLogisticsScore()); //物流评分
		record.setServiceScore(model.getServiceScore()); //服务评分	
		record.setType(model.getType()); //类型：1、咨询内容 2、评价晒单 3、我的足迹
		record.setModifier(memberId); //创建人
		record.setModifyTime(new Date());
		record.setCreater(memberId);
		record.setCreateTime(new Date());
		return record;
	}
	
	
}
